<route lang="jsonc" type="page">
{
"style": {
"navigationBarTitleText": "消灭 Emoji",
"navigationBarBackgroundColor": "#fd79a8",
"navigationBarTextStyle": "white"
}
}
</route>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { httpGet, httpPost } from '@/http/http'
import GameSettings from '@/components/GameSettings.vue'
import type { GameSettings as GameSettingsType } from '@/api/gameSettings'

// 临时简单的表情数据，替代 emojibase
const simpleEmojiData = [
  '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
  '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
  '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
  '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
  '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬'
]

defineOptions({
  name: 'EmojiGame',
})

// 游戏设置
const gameSettings = ref({
  gameTime: 60, // 游戏时间（秒），0表示无限模式
  emojiSpeed: 300, // 表情生成间隔（毫秒）
  maxEmojis: 8, // 屏幕最大表情数
  emojiSize: {min: 80, max: 120}, // 表情大小范围
  autoPopTime: 5, // 自动消失时间（秒），0表示不自动消失
})

// 消灭 Emoji 游戏数据
const emojiGame = ref({
  emojis: [],
  score: 0,
  isPlaying: false,
  gameTimer: null,
  timeLeft: 60,
  isInfiniteMode: false,
  // 游戏数据收集相关
  gameRecordId: null, // 游戏记录ID
  gameStartTime: null, // 游戏开始时间
  gameEndTime: null, // 游戏结束时间
  maxCombo: 0, // 最高连击数
  currentCombo: 0, // 当前连击数
  emojiEliminateData: {}, // emoji消除统计数据
  totalEliminatedCount: 0, // 总消灭数量
})

// 游戏设置组件引用
const gameSettingsRef = ref()

// 表情ID计数器，确保每个表情都有唯一ID
let emojiIdCounter = 0

// 表情库 - 从 emojibase 获取表情数据
const emojiLibrary = ref([])

// 初始化表情库
function initEmojiLibrary() {
  console.log('初始化表情库')
  emojiLibrary.value = simpleEmojiData
  console.log('表情库初始化完成，表情数量:', emojiLibrary.value.length)
}

// 计算可见的表情（现在所有表情都是可见的，因为隐藏的会被直接删除）
const visibleEmojis = computed(() => {
  return emojiGame.value.emojis.filter(emoji => !emoji.disappearing)
})

// 开始游戏
async function startEmojiGame() {
  // 初始化游戏状态
  emojiGame.value.isPlaying = true
  emojiGame.value.score = 0
  emojiGame.value.emojis = []
  emojiGame.value.timeLeft = gameSettings.value.gameTime
  emojiGame.value.isInfiniteMode = gameSettings.value.gameTime === 0
  emojiIdCounter = 0 // 重置ID计数器
  
  // 初始化游戏数据收集
  emojiGame.value.gameStartTime = Date.now()
  emojiGame.value.gameEndTime = null
  emojiGame.value.maxCombo = 0
  emojiGame.value.currentCombo = 0
  emojiGame.value.emojiEliminateData = {}
  emojiGame.value.totalEliminatedCount = 0
  emojiGame.value.gameRecordId = null
  
  // 调用后端开始游戏API
  try {
    const response = await httpPost<any>('/api/miniapp/game/start/emoji_eliminate', {})
    if (response.code === 200 && response.data) {
      emojiGame.value.gameRecordId = response.data
      console.log('游戏开始记录ID:', emojiGame.value.gameRecordId)
    } else {
      console.warn('游戏开始记录失败:', response.msg)
    }
  } catch (error) {
    console.error('游戏开始接口调用失败:', error)
  }

  // 定期生成表情
  const emojiTimer = setInterval(() => {
    // 只计算未消失的表情数量
    const activeEmojis = emojiGame.value.emojis.filter(e => !e.disappearing).length
    if (activeEmojis < gameSettings.value.maxEmojis && emojiLibrary.value.length > 0) {
      // 随机选择表情
      const selectedEmoji = emojiLibrary.value[Math.floor(Math.random() * emojiLibrary.value.length)]

      // 彩虹色系和温暖色系
      const colorPalettes = [
        {h: 340, s: 70, l: 85}, // 粉红色
        {h: 280, s: 60, l: 88}, // 紫色
        {h: 200, s: 65, l: 85}, // 蓝色
        {h: 120, s: 55, l: 85}, // 绿色
        {h: 60, s: 70, l: 88}, // 黄色
        {h: 30, s: 75, l: 85}, // 橙色
        {h: 0, s: 65, l: 88}, // 红色
        {h: 180, s: 60, l: 85}, // 青色
      ]
      const selectedColor = colorPalettes[Math.floor(Math.random() * colorPalettes.length)]

      // 消失动画样式
      const disappearStyles = ['vanish1', 'vanish2', 'vanish3', 'vanish4', 'vanish5']
      const selectedDisappearStyle = disappearStyles[Math.floor(Math.random() * disappearStyles.length)]

      const emoji = {
        id: ++emojiIdCounter, // 使用递增计数器生成唯一ID
        x: Math.random() * 600,
        y: Math.random() * 1000,
        size: gameSettings.value.emojiSize.min + Math.random() * (gameSettings.value.emojiSize.max - gameSettings.value.emojiSize.min),
        emoji: selectedEmoji,
        backgroundColor: `hsl(${selectedColor.h}, ${selectedColor.s}%, ${selectedColor.l}%)`,
        disappearStyle: selectedDisappearStyle, // 消失样式
        disappearing: false,
        autoPopTimer: null, // 自动消失定时器
      }
      emojiGame.value.emojis.push(emoji)

      // 设置自动消失定时器
      if (gameSettings.value.autoPopTime > 0) {
        emoji.autoPopTimer = setTimeout(() => {
          autoDisappearEmoji(emoji.id)
        }, gameSettings.value.autoPopTime * 1000)
      }
    }
  }, gameSettings.value.emojiSpeed)

  // 分离倒计时计时器（每秒执行一次）
  let countdownTimer = null
  if (!emojiGame.value.isInfiniteMode) {
    countdownTimer = setInterval(() => {
      emojiGame.value.timeLeft--
      if (emojiGame.value.timeLeft <= 0) {
        stopGame()
      }
    }, 1000) // 每1000毫秒（1秒）执行一次
  }

  // 将两个计时器保存起来
  emojiGame.value.gameTimer = {
    emojiTimer,
    countdownTimer,
  }
}

// 祝福语数据（从接口获取）
const blessings = ref([])
const audioConfigs = ref([])

// 加载祝福语配置
async function loadBlessings() {
  try {
    const response = await httpGet<any>('/api/miniapp/game/blessings/emoji_eliminate')
    
    if (response.code === 200 && response.data) {
      blessings.value = response.data.map(item => item.blessingText)
      console.log('Emoji祝福语加载成功:', blessings.value.length, '条')
    } else {
      console.warn('祝福语加载失败，使用默认数据')
      // 如果接口失败，使用默认祝福语
      blessings.value = ['太棒了', '好厉害', 'Awesome', 'Great Job', '消灭成功']
    }
  } catch (error) {
    console.error('祝福语加载异常:', error)
    // 异常时使用默认祝福语
    blessings.value = ['太棒了', '好厉害', 'Awesome', 'Great Job', '消灭成功']
  }
}

// 加载音效配置
async function loadAudioConfigs() {
  try {
    const response = await httpGet<any>('/api/miniapp/game/audios/emoji_eliminate')
    
    if (response.code === 200 && response.data) {
      audioConfigs.value = response.data
      console.log('Emoji音效配置加载成功:', audioConfigs.value.length, '条')
    } else {
      console.warn('音效配置加载失败，使用默认音效')
    }
  } catch (error) {
    console.error('音效配置加载异常:', error)
  }
}

// 祝福文字数组
const blessingsText = ref([])

// 祝福文字ID计数器
let blessingsIdCounter = 0

// 记录emoji消除数据
function recordEmojiEliminate(emoji: any) {
  const emojiChar = emoji.emoji
  const currentTime = Date.now()
  
  // 获取emoji的unicode编码
  const emojiUnicode = emojiChar.codePointAt(0)?.toString(16).toUpperCase() || ''
  
  // 增加总消灭数量
  emojiGame.value.totalEliminatedCount++
  
  // 记录或更新emoji消除数据
  if (!emojiGame.value.emojiEliminateData[emojiUnicode]) {
    emojiGame.value.emojiEliminateData[emojiUnicode] = {
      emojiUnicode: emojiUnicode,
      emojiChar: emojiChar,
      eliminatedCount: 0,
      firstEliminatedTime: currentTime,
      lastEliminatedTime: currentTime
    }
  }
  
  // 更新数据
  const emojiData = emojiGame.value.emojiEliminateData[emojiUnicode]
  emojiData.eliminatedCount++
  emojiData.lastEliminatedTime = currentTime
  
  console.log(`消灭emoji: ${emojiChar}, 总计: ${emojiData.eliminatedCount}次`)
}

// 消灭表情
function eliminateEmoji(emojiId: number) {
  const emoji = emojiGame.value.emojis.find(e => e.id === emojiId)
  if (emoji && !emoji.disappearing) {
    // 清除自动消失定时器
    if (emoji.autoPopTimer) {
      clearTimeout(emoji.autoPopTimer)
      emoji.autoPopTimer = null
    }

    // 立即标记为正在消失，防止重复点击同一个表情
    emoji.disappearing = true

    // 记录emoji消除数据
    recordEmojiEliminate(emoji)

    // 更新连击数
    emojiGame.value.currentCombo++
    if (emojiGame.value.currentCombo > emojiGame.value.maxCombo) {
      emojiGame.value.maxCombo = emojiGame.value.currentCombo
    }

    // 创建祝福文字
    createBlessingText(emoji)

    // 播放音效
    playEliminateSound()

    // 立即增加分数
    emojiGame.value.score += 10

    // 延迟后销毁表情
    setTimeout(() => {
      const index = emojiGame.value.emojis.findIndex(e => e.id === emojiId)
      if (index > -1) {
        emojiGame.value.emojis.splice(index, 1)
      }
    }, 500)
  }
}

// 自动消失表情（超时）
function autoDisappearEmoji(emojiId: number) {
  const emoji = emojiGame.value.emojis.find(e => e.id === emojiId)
  if (emoji && !emoji.disappearing) {
    // 立即标记为正在消失
    emoji.disappearing = true

    // 重置连击数（因为没有成功点击）
    emojiGame.value.currentCombo = 0

    // 自动消失不创建祝福文字，不增加分数，播放音效
    playEliminateSound()
    // 只是让表情静默消失

    // 延迟后销毁表情
    setTimeout(() => {
      const index = emojiGame.value.emojis.findIndex(e => e.id === emojiId)
      if (index > -1) {
        emojiGame.value.emojis.splice(index, 1)
      }
    }, 500)
  }
}

// 创建祝福文字特效
function createBlessingText(emoji: any) {
  // 确保有祝福语数据
  if (!blessings.value || blessings.value.length === 0) {
    console.warn('暂无祝福语数据')
    return
  }
  
  // 随机选择一个祝福语
  const randomBlessing = blessings.value[Math.floor(Math.random() * blessings.value.length)]

  // 创建祝福文字对象
  const blessingText = {
    id: ++blessingsIdCounter,
    text: randomBlessing,
    x: emoji.x + emoji.size / 2, // 以表情中心为起点
    y: emoji.y + emoji.size / 2,
    color: emoji.backgroundColor,
    visible: true,
  }

  // 添加到祝福文字数组
  blessingsText.value.push(blessingText)

  // 1.5秒后移除文字
  setTimeout(() => {
    const index = blessingsText.value.findIndex(b => b.id === blessingText.id)
    if (index > -1) {
      blessingsText.value.splice(index, 1)
    }
  }, 1500)
}

// 播放消除音效
function playEliminateSound() {
  try {
    // 先尝试使用接口配置的音效
    const eliminateAudioConfig = audioConfigs.value.find(config => config.audioType === 'eliminate')
    let audioUrl = 'https://example-luckcoder.oss-cn-beijing.aliyuncs.com/2025/09/09/a1b93e8c227842e9bd5f1428f12567b6.wav'
    let volume = 0.6
    
    if (eliminateAudioConfig) {
      audioUrl = eliminateAudioConfig.audioUrl || audioUrl
      volume = eliminateAudioConfig.volume ? Number(eliminateAudioConfig.volume) / 100 : volume
      console.log('使用配置音效:', audioUrl, '音量:', volume)
    }
    
    const audioContext = uni.createInnerAudioContext()
    audioContext.src = audioUrl
    audioContext.volume = volume

    audioContext.onError((err) => {
      console.log('网络音频播放失败，使用备用方案:', err)
      // 根据配置的fallbackType决定备用方案
      if (eliminateAudioConfig && eliminateAudioConfig.fallbackType === 'silent') {
        // 静默处理
        return
      } else if (eliminateAudioConfig && eliminateAudioConfig.fallbackType === 'toast') {
        // 提示处理
        uni.showToast({
          title: '消灭！',
          icon: 'none',
          duration: 200,
          mask: false,
        })
      } else {
        // 默认生成音效
        generateEliminateSound()
      }
    })

    audioContext.onCanplay(() => {
      audioContext.play()
    })

    audioContext.onEnded(() => {
      audioContext.destroy()
    })
  } catch (error) {
    console.log('音效播放失败:', error)
    generateEliminateSound()
  }
}

// 使用Web Audio API生成消除音效
function generateEliminateSound() {
  try {
    // 在H5环境下使用Web Audio API
    // #ifdef H5
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()

    // 创建音频节点
    const oscillator = audioContext.createOscillator()
    const gainNode = audioContext.createGain()

    // 连接音频节点
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.destination)

    // 设置音效参数（模拟消除声）
    oscillator.frequency.setValueAtTime(600, audioContext.currentTime)
    oscillator.frequency.exponentialRampToValueAtTime(1200, audioContext.currentTime + 0.1)

    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime)
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1)

    // 播放音效
    oscillator.start(audioContext.currentTime)
    oscillator.stop(audioContext.currentTime + 0.1)
    // #endif

    // 在非H5环境下使用系统提示音作为替代
    // #ifndef H5
    uni.showToast({
      title: '消灭！',
      icon: 'none',
      duration: 200,
      mask: false,
    })
    // #endif
  } catch (error) {
    console.log('生成音效失败:', error)
  }
}

// 停止游戏
async function stopGame() {
  if (emojiGame.value.gameTimer) {
    if (emojiGame.value.gameTimer.emojiTimer) {
      clearInterval(emojiGame.value.gameTimer.emojiTimer)
    }
    if (emojiGame.value.gameTimer.countdownTimer) {
      clearInterval(emojiGame.value.gameTimer.countdownTimer)
    }
    emojiGame.value.gameTimer = null
  }

  // 清理所有表情的自动消失定时器
  emojiGame.value.emojis.forEach((emoji) => {
    if (emoji.autoPopTimer) {
      clearTimeout(emoji.autoPopTimer)
      emoji.autoPopTimer = null
    }
  })

  emojiGame.value.isPlaying = false

  // 设置游戏结束时间
  emojiGame.value.gameEndTime = Date.now()
  
  // 提交游戏统计数据
  await submitGameStats()

  // 显示游戏结束提示
  uni.showModal({
    title: '游戏结束',
    content: `恭喜你消灭了 ${emojiGame.value.totalEliminatedCount} 个表情，得到 ${emojiGame.value.score} 分！连击最高：${emojiGame.value.maxCombo}`,
    confirmText: '查看统计',
    cancelText: '好的',
    success: (res) => {
      if (res.confirm) {
        // TODO: 跳转到游戏统计页面
        showGameStats()
      } else {
        // 用户点击"好的"，不执行任何操作，回到游戏开始界面
        console.log('用户确认游戏结束')
      }
    },
  })
}

// 提交游戏统计数据
async function submitGameStats() {
  if (!emojiGame.value.gameRecordId) {
    console.warn('没有游戏记录ID，无法提交统计数据')
    return
  }
  
  try {
    // 计算游戏时长（秒）
    const playTime = Math.floor((emojiGame.value.gameEndTime - emojiGame.value.gameStartTime) / 1000)
    
    // 确定游戏结果
    let gameResult = 'completed'
    if (emojiGame.value.isInfiniteMode) {
      gameResult = 'quit' // 无限模式下停止算退出
    } else if (emojiGame.value.timeLeft <= 0) {
      gameResult = 'timeout' // 时间到了算超时
    }
    
    // 转换emoji消除数据为数组格式
    const emojiDetails = Object.values(emojiGame.value.emojiEliminateData)
    
    // 构造提交数据
    const gameFinishData = {
      gameCode: 'emoji_eliminate',
      finalScore: emojiGame.value.score,
      playTime: playTime,
      gameResult: gameResult,
      gameMode: emojiGame.value.isInfiniteMode ? 'infinite' : 'normal',
      totalEliminatedCount: emojiGame.value.totalEliminatedCount,
      maxCombo: emojiGame.value.maxCombo,
      extraData: JSON.stringify({
        emojiVariety: Object.keys(emojiGame.value.emojiEliminateData).length,
        avgCombo: emojiGame.value.totalEliminatedCount > 0 ? emojiGame.value.maxCombo / emojiGame.value.totalEliminatedCount : 0
      }),
      emojiDetails: emojiDetails
    }
    
    console.log('提交游戏统计数据:', gameFinishData)
    
    const response = await httpPost<any>(`/api/miniapp/game/finish/${emojiGame.value.gameRecordId}`, gameFinishData)
    if (response.code === 200) {
      console.log('游戏统计数据提交成功')
    } else {
      console.warn('游戏统计数据提交失败:', response.msg)
    }
  } catch (error) {
    console.error('游戏统计数据提交异常:', error)
  }
}

// 显示游戏统计（临时函数，后续会有专门的统计页面）
function showGameStats() {
  const playTime = Math.floor((emojiGame.value.gameEndTime - emojiGame.value.gameStartTime) / 1000)
  
  // 构建当前游戏统计数据
  const gameData = {
    score: emojiGame.value.score,
    eliminatedCount: emojiGame.value.totalEliminatedCount,
    maxCombo: emojiGame.value.maxCombo,
    playTime: playTime,
    gameResult: 'completed', // 这里可以根据实际游戏结束原因设置
    emojiDetails: Object.entries(emojiGame.value.emojiEliminateData).map(([emojiUnicode, data]: any) => ({
      emojiUnicode: emojiUnicode,
      emojiChar: data.emojiChar,
      eliminatedCount: data.eliminatedCount,
      firstEliminatedTime: data.firstEliminatedTime,
      lastEliminatedTime: data.lastEliminatedTime
    }))
  }
  
  // 跳转到统计页面
  uni.navigateTo({
    url: `/pages/relax/game/emoji/stats?gameData=${encodeURIComponent(JSON.stringify(gameData))}`
  })
}

// 打开游戏设置
function openGameSettings() {
  gameSettingsRef.value?.openPopup()
}

// 处理设置变更
function onSettingsChanged(settings: GameSettingsType) {
  gameSettings.value = {
    gameTime: settings.gameTime,
    emojiSpeed: settings.emojiSpeed,
    maxEmojis: settings.maxEmojis,
    emojiSize: { 
      min: settings.emojiSizeMin || 80, 
      max: settings.emojiSizeMax || 120 
    },
    autoPopTime: settings.autoPopTime || 0
  }
  
  // 更新无限模式状态
  emojiGame.value.isInfiniteMode = gameSettings.value.gameTime === 0
  emojiGame.value.timeLeft = gameSettings.value.gameTime || 60
  
  // 如果游戏正在进行，重新启动游戏
  if (emojiGame.value.isPlaying) {
    stopGame()
    setTimeout(() => {
      startEmojiGame()
    }, 500)
  }
}

// 应用设置并重置游戏
function applySettingsAndReset() {
  if (emojiGame.value.gameTimer) {
    if (emojiGame.value.gameTimer.emojiTimer) {
      clearInterval(emojiGame.value.gameTimer.emojiTimer)
    }
    if (emojiGame.value.gameTimer.countdownTimer) {
      clearInterval(emojiGame.value.gameTimer.countdownTimer)
    }
    emojiGame.value.gameTimer = null
  }

  // 清理所有表情的自动消失定时器
  emojiGame.value.emojis.forEach((emoji) => {
    if (emoji.autoPopTimer) {
      clearTimeout(emoji.autoPopTimer)
      emoji.autoPopTimer = null
    }
  })

  emojiGame.value.isPlaying = false
  emojiGame.value.emojis = []
  emojiGame.value.score = 0
  emojiGame.value.timeLeft = gameSettings.value.gameTime
  emojiGame.value.isInfiniteMode = gameSettings.value.gameTime === 0
  emojiIdCounter = 0 // 重置ID计数器
  blessingsText.value = [] // 清空祝福文字
  blessingsIdCounter = 0 // 重置祝福文字ID计数器
}


// 跳转到排行榜页面
function goToRanking() {
  uni.navigateTo({
    url: '/pages/relax/game/emoji/ranking'
  })
}

// 跳转到个人统计页面
function goToHistory() {
  uni.navigateTo({
    url: '/pages/relax/game/emoji/stats'
  })
}


// 组件加载时初始化表情库和加载配置数据
onMounted(() => {
  console.log('=== 页面已加载 ===')
  console.log('emojiGame.value:', emojiGame.value)
  
  try {
    console.log('开始初始化表情库...')
    initEmojiLibrary()
    console.log('表情库初始化完成')
    
    console.log('=== 页面初始化完成，跳过其他初始化 ===')
  } catch (error) {
    console.error('页面初始化错误:', error)
  }
})

onUnmounted(() => {
  if (emojiGame.value.gameTimer) {
    if (emojiGame.value.gameTimer.emojiTimer) {
      clearInterval(emojiGame.value.gameTimer.emojiTimer)
    }
    if (emojiGame.value.gameTimer.countdownTimer) {
      clearInterval(emojiGame.value.gameTimer.countdownTimer)
    }
  }

  // 清理所有表情的自动消失定时器
  emojiGame.value.emojis.forEach((emoji) => {
    if (emoji.autoPopTimer) {
      clearTimeout(emoji.autoPopTimer)
      emoji.autoPopTimer = null
    }
  })

  blessingsText.value = [] // 清空祝福文字
  
  // 移除事件监听器
  uni.$off('startNewGame')
})
</script>

<template>
  <view class="emoji-game-container">
    
    <!-- 游戏信息栏 -->
    <view class="game-header">
      <view class="score-info">
        得分: {{ emojiGame.score }}
      </view>
      <view class="time-info">
        <text v-if="!emojiGame.isInfiniteMode">时间: {{ emojiGame.timeLeft }}s</text>
        <text v-else>无限模式</text>
      </view>
    </view>

    <!-- 游戏区域 -->
    <view class="game-area">
      <!-- 未开始状态 -->
      <view v-if="!emojiGame.isPlaying && emojiGame.score === 0" class="game-start">
        <view class="start-icon-container">
          <view class="i-mdi-heart start-icon"></view>
          <view class="icon-glow"></view>
        </view>
        <view class="start-title">
          消灭 Emoji
        </view>
        <view class="start-desc">
          点击屏幕上的表情来消灭它们<br/>
          挑战你的反应速度和手眼协调能力
        </view>
        <button class="start-btn" @click="startEmojiGame">
          <view class="i-fluent-emoji-meme-24-regular btn-icon"></view>
          <text>开始游戏</text>
        </button>
        
        <!-- 功能入口按钮 -->
        <view class="function-buttons">
          <button class="func-btn ranking-btn" @click="goToRanking">
            <view class="i-mdi-trophy func-icon"></view>
            <text class="func-text">排行榜</text>
          </button>
          <button class="func-btn history-btn" @click="goToHistory">
            <view class="i-mynaui-academic-hat-solid func-icon"></view>
            <text class="func-text">个人统计</text>
          </button>
          <button class="func-btn settings-btn" @click="console.log('游戏设置点击')">
            <view class="i-solar-gameboy-broken func-icon"></view>
            <text class="func-text">游戏设置</text>
          </button>
        </view>
      </view>

      <!-- 游戏进行中 -->
      <view v-if="emojiGame.isPlaying" class="emoji-container">
        <view
            v-for="emoji in visibleEmojis"
            :key="emoji.id"
            class="emoji"
            :class="{
            disappearing: emoji.disappearing,
            [emoji.disappearStyle]: emoji.disappearing,
          }"
            :style="{
            left: `${emoji.x}rpx`,
            top: `${emoji.y}rpx`,
            width: `${emoji.size}rpx`,
            height: `${emoji.size}rpx`,
            backgroundColor: emoji.backgroundColor,
          }"
            @touchstart.stop="eliminateEmoji(emoji.id)"
            @click.stop="eliminateEmoji(emoji.id)"
        >
          {{ emoji.emoji }}
        </view>

        <!-- 祝福文字特效 -->
        <view
            v-for="blessing in blessingsText"
            :key="blessing.id"
            class="blessing-text"
            :style="{
            left: `${blessing.x}rpx`,
            top: `${blessing.y}rpx`,
            color: blessing.color,
          }"
        >
          {{ blessing.text }}
        </view>
      </view>
    </view>

    <!-- 游戏控制按钮 -->
    <view class="game-controls">
      <button
          v-if="!emojiGame.isPlaying && emojiGame.score > 0"
          class="control-btn restart-btn"
          @click="startEmojiGame"
      >
        重新开始
      </button>
      <button
          v-if="emojiGame.isPlaying"
          class="control-btn stop-btn"
          @click="stopGame"
      >
        结束游戏
      </button>
    </view>

    <!-- 游戏说明 -->
    <view class="game-instructions">
      <view class="instruction-title">
        游戏规则
      </view>
      <view class="instruction-list">
        <view class="instruction-item">
          • 点击屏幕上的表情来消灭它们
        </view>
        <view class="instruction-item">
          • 每个表情价值10分
        </view>
        <view class="instruction-item">
          • {{
            emojiGame.isInfiniteMode ? '无限模式，尽情享受消灭表情的乐趣' : `游戏时间${gameSettings.gameTime}秒，争取更高分数`
          }}
        </view>
        <view class="instruction-item">
          • 表情会不断出现，手速要快哦
        </view>
        <view class="instruction-item">
          • {{
            gameSettings.autoPopTime > 0 ? `表情会在${gameSettings.autoPopTime}秒后自动消失` : '表情不会自动消失，尽快点击获得分数'
          }}
        </view>
      </view>
    </view>

    <!-- 游戏设置组件 - 暂时注释掉测试 -->
    <!-- <GameSettings 
      ref="gameSettingsRef"
      game-code="emoji_eliminate" 
      @settings-changed="onSettingsChanged"
    /> -->
  </view>
</template>

<style lang="scss" scoped>
.emoji-game-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #fd79a8 0%, #fdcb6e 100%);
  padding: 20rpx;
  padding-bottom: env(safe-area-inset-bottom);
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(circle at 30% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.08) 0%, transparent 50%);
    pointer-events: none;
  }
}

// 游戏信息栏
.game-header {
  display: flex;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.15);
  padding: 24rpx 36rpx;
  border-radius: 28rpx;
  margin-bottom: 24rpx;
  backdrop-filter: blur(20rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.score-info,
.time-info {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

// 游戏区域
.game-area {
  height: 1200rpx;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 32rpx;
  margin-bottom: 30rpx;
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(20rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.15);
  box-shadow: 
    0 20rpx 60rpx rgba(0, 0, 0, 0.15),
    inset 0 1rpx 0 rgba(255, 255, 255, 0.2);
}

// 游戏开始界面
.game-start {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #fff;
  text-align: center;
  padding: 60rpx 40rpx;
}

// 图标容器和发光效果
.start-icon-container {
  position: relative;
  margin-bottom: 40rpx;
}

.start-icon {
  font-size: 140rpx;
  color: #fff;
  filter: drop-shadow(0 4rpx 12rpx rgba(0, 0, 0, 0.3));
  animation: float 3s ease-in-out infinite;
}

.icon-glow {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200rpx;
  height: 200rpx;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, transparent 70%);
  border-radius: 50%;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20rpx); }
}

@keyframes pulse {
  0%, 100% { opacity: 0.6; transform: translate(-50%, -50%) scale(1); }
  50% { opacity: 0.9; transform: translate(-50%, -50%) scale(1.1); }
}

.start-title {
  font-size: 52rpx;
  font-weight: 800;
  margin-bottom: 24rpx;
  background: linear-gradient(135deg, #fff 0%, rgba(255, 255, 255, 0.8) 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
}

.start-desc {
  font-size: 28rpx;
  line-height: 1.8;
  margin-bottom: 50rpx;
  opacity: 0.9;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  max-width: 500rpx;
}

.start-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border: none;
  padding: 32rpx 64rpx;
  border-radius: 60rpx;
  font-size: 34rpx;
  font-weight: 700;
  box-shadow: 0 12rpx 32rpx rgba(79, 172, 254, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  gap: 16rpx;

  &:active {
    transform: translateY(4rpx) scale(0.98);
    box-shadow: 0 6rpx 16rpx rgba(79, 172, 254, 0.5);
  }
}

.btn-icon {
  font-size: 36rpx;
}

// 功能按钮容器
.function-buttons {
  display: flex;
  justify-content: center;
  gap: 24rpx;
  margin-top: 60rpx;
  flex-wrap: wrap;
}

// 功能按钮样式
.func-btn {
  background: rgba(255, 255, 255, 0.12);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 20rpx 28rpx;
  border-radius: 50rpx;
  backdrop-filter: blur(20rpx);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  min-width: 120rpx;
  
  &:active {
    transform: translateY(2rpx) scale(0.96);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.25);
    background: rgba(255, 255, 255, 0.18);
  }
}

.func-icon {
  font-size: 32rpx;
  margin-bottom: 4rpx;
}

.func-text {
  font-size: 24rpx;
  font-weight: 500;
  opacity: 0.95;
}

// 按钮特色样式
.ranking-btn:active {
  background: rgba(255, 193, 7, 0.2) !important;
}

.history-btn:active {
  background: rgba(138, 43, 226, 0.2) !important;
}

.settings-btn:active {
  background: rgba(52, 152, 219, 0.2) !important;
}

// 表情容器
.emoji-container {
  width: 100%;
  height: 100%;
  position: relative;
  user-select: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  touch-action: manipulation;
}

// 表情元素
.emoji {
  position: absolute;
  border-radius: 50%;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  cursor: pointer;
  user-select: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  transition: all 0.2s ease;
  backdrop-filter: blur(8rpx);
  border: 2rpx solid rgba(255, 255, 255, 0.3);

  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  font-weight: bold;

  &:active {
    transform: scale(0.9);
  }

  // 消失动画样式
  &.disappearing {
    pointer-events: none;
  }

  // 消失动画1 - 缩放淡出
  &.vanish1 {
    animation: vanish1 0.5s ease-out forwards;
  }

  // 消失动画2 - 旋转淡出
  &.vanish2 {
    animation: vanish2 0.5s ease-out forwards;
  }

  // 消失动画3 - 震动淡出
  &.vanish3 {
    animation: vanish3 0.5s ease-out forwards;
  }

  // 消失动画4 - 向上飞出
  &.vanish4 {
    animation: vanish4 0.5s ease-out forwards;
  }

  // 消失动画5 - 脉冲淡出
  &.vanish5 {
    animation: vanish5 0.5s ease-out forwards;
  }
}

// 祝福文字特效
.blessing-text {
  position: absolute;
  font-size: 24rpx;
  font-weight: 600;
  pointer-events: none;
  user-select: none;
  z-index: 100;
  text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
  animation: blessingRise 1.5s ease-out forwards;
  transform-origin: center;
}

// 消失动画定义
@keyframes vanish1 {
  0% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: scale(0) rotate(180deg);
    opacity: 0;
  }
}

@keyframes vanish2 {
  0% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: scale(1.5) rotate(360deg);
    opacity: 0;
  }
}

@keyframes vanish3 {
  0% {
    transform: scale(1) translateX(0);
    opacity: 1;
  }
  20% {
    transform: scale(1.1) translateX(-10rpx);
  }
  40% {
    transform: scale(1.1) translateX(10rpx);
  }
  60% {
    transform: scale(1.1) translateX(-5rpx);
  }
  80% {
    transform: scale(1.1) translateX(5rpx);
  }
  100% {
    transform: scale(0) translateX(0);
    opacity: 0;
  }
}

@keyframes vanish4 {
  0% {
    transform: translateY(0) scale(1);
    opacity: 1;
  }
  100% {
    transform: translateY(-200rpx) scale(0.5);
    opacity: 0;
  }
}

@keyframes vanish5 {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  25% {
    transform: scale(1.3);
    opacity: 0.8;
  }
  50% {
    transform: scale(0.9);
    opacity: 0.6;
  }
  75% {
    transform: scale(1.2);
    opacity: 0.4;
  }
  100% {
    transform: scale(0);
    opacity: 0;
  }
}

// 祝福文字上升动画
@keyframes blessingRise {
  0% {
    transform: translateY(0) scale(0.8);
    opacity: 0;
  }
  20% {
    transform: translateY(-20rpx) scale(1.2);
    opacity: 1;
  }
  100% {
    transform: translateY(-80rpx) scale(1);
    opacity: 0;
  }
}

// 游戏控制按钮
.game-controls {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.control-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: none;
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  font-size: 28rpx;
  font-weight: 600;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 0.3);
  }
}

.restart-btn {
  background: linear-gradient(135deg, #00b894, #00cec9);
}

.stop-btn {
  background: linear-gradient(135deg, #e17055, #d63031);
}

.reset-btn {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
}

// 游戏说明
.game-instructions {
  background: rgba(255, 255, 255, 0.95);
  margin: 20rpx 10rpx;
  padding: 30rpx;
  border-radius: 24rpx;
  backdrop-filter: blur(10rpx);
}

.instruction-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 24rpx;
}

.instruction-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.instruction-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  padding: 12rpx 0;
}

// 设置对话框

// 响应式适配
@media screen and (min-width: 768rpx) {
  .emoji-game-container {
    padding: 40rpx;
  }

  .game-area {
    height: 1400rpx;
  }
}
</style>
